package com.allwees.bs.c.module.product.service.impl;

import com.allwees.bs.c.module.product.repository.CategoryRepository;
import com.allwees.bs.c.module.product.service.CategoryService;
import com.allwees.bs.c.module.product.vo.CategoryVO;
import com.allwees.bs.core.model.constant.CacheName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    @Cacheable(cacheNames = CacheName.APP_CATEGORY,key = "'all'",sync = true)
    public List<CategoryVO> getAllCategories() {
        log.info("===> load categories from database...");
        List<CategoryVO> categories = new ArrayList<>();
        //热销类目特殊处理
        categories.add(CategoryVO.hotSell());
        categories.addAll(rootCategories());
        return categories;
    }

    private List<CategoryVO> rootCategories() {
        return this.categoryRepository.findChildCategories("0").stream().map(CategoryVO::new).collect(Collectors.toList());
    }
}
